/**
 *
 * Copyright 2011 Jwchen. All rights reserved.
 * JsonParserUtil.java
 *
 */
package com.hotau.util;

import java.io.IOException;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

/**
 *@author jwchen (jwchen1001@gmail.com)
 *@date 2011-12-9
 */
public class JsonParserUtil
{
    private static ObjectMapper mapper = new ObjectMapper();
    
    static
    {
        mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    public static String Object2JsonStr(Object data)
    {
        try
        {
            return mapper.writeValueAsString(data);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public static Object str2Object(String jsonStr, Class<?> c)
    {
        try
        {
            return mapper.readValue(jsonStr, c);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            
            return null;
        }
    }
    
    public static Object str2ObjectByTag(String jsonStr, String tag, Class<?> c)
    {
        try
        {
            JsonNode rootNode = mapper.readTree(jsonStr);
            return mapper.readValue(rootNode.path(tag), c);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public static Object str2ObjectByTag(String jsonStr, String tag, TypeReference<?> valueTypeRef)
    {
        try
        {
            JsonNode rootNode = mapper.readTree(jsonStr);
            String[] paths = tag.split("/");
            JsonNode targetNode = rootNode;
            for(String str : paths)
            {
                targetNode = targetNode.path(str);
            }
            return mapper.readValue(targetNode, valueTypeRef);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }
    
    public static Object str2Object(String jsonStr, TypeReference<?> valueTypeRef)
    {
        try
        {
            return mapper.readValue(jsonStr, valueTypeRef);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            
            return null;
        }
    }
    
}
